package com.common.event;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.event.listener.EventMessageListenerRouter;
import com.common.event.queue.Queue;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;

/**
 * 
 * @Title: EventBusHolder.java
 * @Package com.common.event
 * @Description:事件总线
 * @author tangzhibin
 * @date 2016年9月28日
 * @version V1.0
 */

public class CommonEventBus {
	
	public static final Logger	LOGGER	= LoggerFactory.getLogger(CommonEventBus.class);

	private EventMessageListenerRouter eventListenerRouter;
	
	private Map<String,Queue> queueMapping=new HashMap<String,Queue>();
	
	public CommonEventBus(){
		
	}

	private static class EventBusHolder {
		private static ExecutorManager	executorManager	= new ExecutorManager();
		private static EventBus			eventBus		= new AsyncEventBus(executorManager.getPool());
	}

	public EventBus getEventBus() {
		return EventBusHolder.eventBus;
	}
	
	@PostConstruct
	public void init() {
		this.getEventBus().register(eventListenerRouter);
	}

	@PreDestroy
	public void destoryEventBus() {
		if(!EventBusHolder.executorManager.getPool().isShutdown()){
			EventBusHolder.executorManager.shutdown();
		}
	}

	/**
	 * 事件消息转发
	 * 
	 * @param eventMessage
	 */
	public void postEvnetMessage(EventMessage eventMessage) {
		if(eventMessage!=null){
			if(eventMessage.getEventMessageStorageStrategy()==EventMessageStorageStrategy.STORAGE_IN_JVM){
				/**默认走jvm事件*/
				getEventBus().post(eventMessage);
			}else{
				Queue queue=queueMapping.get(eventMessage.getEventMessageStorageStrategy().toString());
				if(queue!=null){
					queue.pushQueue(eventMessage);
				}else{
					LOGGER.error("no queue for this event....");
				}
			}
		}
	}

	public EventMessageListenerRouter getEventListenerRouter() {
		return eventListenerRouter;
	}

	public void setEventListenerRouter(
			EventMessageListenerRouter eventListenerRouter) {
		this.eventListenerRouter = eventListenerRouter;
	}

	public void setQueueMapping(Map<String, Queue> queueMapping) {
		this.queueMapping = queueMapping;
	}

	public static void main(String[] args) {
	}
}
